package com.qr.activitys.http;

import java.util.HashMap;
import java.util.Map;

import rx.subscriptions.CompositeSubscription;

/**
 * 项目名称：车管所 手机app
 * 类描述：管理所有的观察者
 * 创建人：张飞祥
 * 创建时间：2018/04/18 下午2:17
 * 修改人：张飞祥
 * 修改时间：2018/04/18 下午2:17
 * 修改备注：
 */
public class ApiService {

    //使用CompositeSubscription管理所有的观察者,
    // 在Activity销毁时取消所有订阅。
    // 解决Observable持有Context导致的内存泄露的问题。
    private Map<Integer, CompositeSubscription> mCompositeSubByTaskId;

    private static class ApiServiceHolder {
        private static final ApiService INSTANCE = new ApiService();
    }


    private ApiService() {}


    public static final ApiService getApiService() {

        return ApiServiceHolder.INSTANCE;
    }


    public void initService() {
        mCompositeSubByTaskId = new HashMap<Integer, CompositeSubscription>();
    }


    public void addCompositeSub(int taskId) {
        CompositeSubscription compositeSubscription;
        if (mCompositeSubByTaskId.get(taskId) == null) {
            compositeSubscription = new CompositeSubscription();
            mCompositeSubByTaskId.put(taskId, compositeSubscription);
        }
    }


    public void removeCompositeSub(int taskId) {
        CompositeSubscription compositeSubscription;
        if (mCompositeSubByTaskId != null &&
                mCompositeSubByTaskId.get(taskId) != null) {
            compositeSubscription = mCompositeSubByTaskId.get(taskId);
            compositeSubscription.unsubscribe();
            mCompositeSubByTaskId.remove(taskId);
        }
    }


    public CompositeSubscription getCompositeSubscription(int taskId) {
        CompositeSubscription compositeSubscription;
        if (mCompositeSubByTaskId.get(taskId) == null) {
            compositeSubscription = new CompositeSubscription();
            mCompositeSubByTaskId.put(taskId, compositeSubscription);
        } else {
            compositeSubscription = mCompositeSubByTaskId.get(taskId);
        }
        return compositeSubscription;
    }
}
